<?php


namespace app\component\tencentCloud\sms;

use app\qo\SmsQo;
use app\services\tencentCloud\sms\SmsUtils;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Sms\V20210111\SmsClient;

class TencentCloudSms
{
    public string $secretId;
    public string $secretKey;
    public string $smsSdkAppId;
    public string $signName;
    public int $timeout;
    public string $endpoint = 'sms.tencentcloudapi.com';

    private function createClient()
    {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取

            $cred = new Credential($this->secretId, $this->secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint($this->endpoint);
//            $httpProfile->setReqMethod(HttpProfile::$REQ_POST);
//            $httpProfile->setReqTimeout($this->timeout);

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            return new SmsClient($cred, "ap-beijing", $clientProfile);

        } catch (TencentCloudSDKException $e) {
            echo $e->getMessage();
        }
    }

    /**
     * 短信发送
     * https://cloud.tencent.com/document/api/382/38778
     * @param SmsQo $qo
     * @return string
     * @author ysk
     */
    public function sendSms(SmsQo $qo): string
    {
        // 实例化一个请求对象,每个接口都会对应一个request对象
        $req = new SendSmsRequest();
        //短信应用ID
        $params['SmsSdkAppId'] = $this->smsSdkAppId;
        $params['TemplateID'] = $qo->templateId;
        $params['TemplateParamSet'] = $qo->templateParamSet;

        //获取地区信息
        $area = SmsUtils::getRegion($qo->code);

        //国内发送需要签名
        if ($qo->code == 'CN') {
            $params['SignName'] = $this->signName;
        }

        //拼接地区码 单次两百个
        $phones = [
            SmsUtils::addCode($area['area_code'], $qo->phoneNumberSet)
        ];

        $params['PhoneNumberSet'] = $phones;

        $req->fromJsonString(json_encode($params));

        // 返回的resp是一个BankSlipOCRResponse的实例，与请求对象对应
        $resp = $this->createClient()->SendSms($req);

        // 输出json格式的字符串回包
        return $resp->toJsonString();

    }
}